from json import JSONEncoder
from django.db.models.query import QuerySet
from django.shortcuts import redirect, render_to_response
from django.template import RequestContext
from com.kjssoft.rainbow.label.forms import RainbowPhotoFrameLabelCreateForm
from com.kjssoft.rainbow.label.models import RainbowPhotoFrameLabel

__author__ = 'Sea'

class RainbowPhotoFrameLabelJSONEncoder(JSONEncoder):
    def default(self, o):
        if o:
            if isinstance(o, RainbowPhotoFrameLabel):
                return o.keyword
            if isinstance(o, list) or isinstance(o, QuerySet):
                labels = []
                for instance in o:
                    labels.append(self.default(instance))
                return labels
        else:
            return []
        return super(RainbowPhotoFrameLabelJSONEncoder, self).default(o)


def save_view_page(request):
    if request.POST:
        form = RainbowPhotoFrameLabelCreateForm(request.POST)
        if form.is_bound and form.is_valid():
            keyword = form.cleaned_data.get('label')
            label_instance = RainbowPhotoFrameLabel.objects.create(keyword)
            return redirect(
                '/rainbow/label/%s/show' % label_instance.id
            )
    form = RainbowPhotoFrameLabelCreateForm(initial={})
    return render_to_response(
        'kjs/rainbow/label/create.html',
        {'form':form},
        context_instance = RequestContext(request)
    )

def show_view_page(request, model_instance):
    pass

